﻿using System.Data;

namespace PBIW.Operating
{
    public sealed class ExpressionCalculator
    {
        private readonly DataTable dataTable;

        public ExpressionCalculator()
        {
            this.dataTable = new DataTable();
        }

        public bool TryCalculate(
            string expression,
            IReadOnlyDictionary<string, string> parameters,
            out int result)
        {
            for (int i = 0; i < 30; i++)
            {
                bool changed = false;
                foreach (var parameter in parameters)
                {
                    var newExpression = expression.Replace(parameter.Key, parameter.Value);
                    if (changed || expression != newExpression)
                        changed = true;
                    expression = newExpression;
                }
                if (!changed)
                    break;
            }

            try
            {
                result = Convert.ToInt32(this.dataTable.Compute(expression, null));
                return true;
            }
            catch
            {
                result = 0;
                return false;
            }
        }
    }
}
